//
//  OPMainTravelNotesController.m
//  OnePiece
//
//  Created by wsy on 15/10/26.
//  Copyright © 2015年 wsy. All rights reserved.
//

#import "OPMainTravelNotesController.h"
#import "OPNoteMainListCell.h"
#import "OPNoteDetailViewController.h"
#import "MJRefresh.h"
#import "FMDatabase.h"

@interface OPMainTravelNotesController () <UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *datasourceArray;
@property (nonatomic, strong) FMDatabase *dataBase;
@property (nonatomic, strong) NSString *startId;

@end

@implementation OPMainTravelNotesController

- (NSMutableArray *)datasourceArray
{
    if (_datasourceArray == nil) {
        self.datasourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _datasourceArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.titleLable.text = @"游记";
    
    
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:(UITableViewStylePlain)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self configureData];
    [self.mainTableView registerClass:[OPNoteMainListCell class] forCellReuseIdentifier:@"cell"];
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self configureData];
        [self.mainTableView.header endRefreshing];
    }];
    self.mainTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self refreshData];
        [self.mainTableView.footer endRefreshing];
    }];
    [self.view addSubview:_mainTableView];
    
    [self openDataBase];
}

- (void)openDataBase
{
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"OnePiece.db"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    if ([_dataBase open]) {
        [_dataBase executeUpdate:@"create table NoteMain (title text, viewCnt integer, likecnt integer, cntp integer, userIcon text, username text, coverpic text)"];
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
    
    FMResultSet *set = [_dataBase executeQuery:@"select *from notemain"];
    while ([set next]) {
        OPNoteMainListModel *m = [[OPNoteMainListModel alloc]init];
        m.title = [set stringForColumn:@"title"];
        m.viewCnt = [set intForColumn:@"viewcnt"];
        m.likeCnt = [set intForColumn:@"likecnt"];
        m.cntP = [set intForColumn:@"cntp"];
        m.owner = @{@"nickname":[set stringForColumn:@"username"],@"avatar":[set stringForColumn:@"usericon"]};
        m.coverpic = [set stringForColumn:@"coverpic"];
        [self.datasourceArray addObject:m];
    }
    [set close];
    [self.mainTableView reloadData];
}

// 网络请求数据
- (void)configureData
{
    [OPRequesterManager requestWithType:GET urlString:@"http://app6.117go.com/demo27/php/interestAction.php?start=&submit=getPlaza6_2&length=12&v=i6.4.2&vc=AppStore&vd=ba172e49ddb4ea7a&lang=zh-Hans&verify=816df343dfa571b9632add87f7cc60ae" parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        [self.datasourceArray removeAllObjects];
        [_dataBase executeUpdate:@"delete from notemain"];
        for (NSDictionary *d in dic[@"obj"][@"list"]) {
            if ([d[@"type"] integerValue] == 4) {
                OPNoteMainListModel *m = [[OPNoteMainListModel alloc]init];
                NSDictionary *dd = d[@"list"][0];
                [m setValuesForKeysWithDictionary:dd];
                [self.datasourceArray addObject:m];
                [_dataBase executeUpdate:@"insert into notemain (title, viewcnt, likecnt, cntp, usericon, username, coverpic) values (?,?,?,?,?,?,?)",m.title, [NSNumber numberWithInteger:m.viewCnt], [NSNumber numberWithInteger:m.likeCnt], [NSNumber numberWithInteger:m.cntP], m.owner[@"avatar"], m.owner[@"nickname"], m.coverpic];

            }
        }
        self.startId = dic[@"obj"][@"start"];
        [self.mainTableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"错误");
    }];
}

- (void)refreshData
{
    NSString *str = [NSString stringWithFormat:@"http://app6.117go.com/demo27/php/interestAction.php?length=12&start=%@&submit=getPlaza6_2&v=a6.4.2&vc=baiduapp&vd=d96969ba524ecd60&verify=80cd2847527a49de04bb8eeb0da7f1d2",_startId];
    [OPRequesterManager requestWithType:GET urlString:str parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        if (data.length == 0) {
            [self.mainTableView.footer endRefreshingWithNoMoreData];
        }
        for (NSDictionary *d in dic[@"obj"][@"list"]) {
            if ([d[@"type"] integerValue] == 4) {
                OPNoteMainListModel *m = [[OPNoteMainListModel alloc]init];
                NSDictionary *dd = d[@"list"][0];
                [m setValuesForKeysWithDictionary:dd];
                [self.datasourceArray addObject:m];
            }
        }
        self.startId = dic[@"obj"][@"start"];
        [self.mainTableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"错误");
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 360 * SCREEN_WIDTH / 616 + 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasourceArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OPNoteMainListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    OPNoteMainListModel *m = self.datasourceArray[indexPath.row];
    [cell configureDataWithModel:m];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell requestDataWithModel:m];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OPNoteMainListModel *m = self.datasourceArray[indexPath.row];
    OPNoteDetailViewController *detailVC = [[OPNoteDetailViewController alloc]init];
    detailVC.noteId = [NSString stringWithFormat:@"%ld",(long)m.noteId];
    [self.navigationController pushViewController:detailVC animated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
